 #include <iostream>
 #include <string>
 #include <memory>
 
 using namespace std;
  
 class ShareResource {
 public:
    
     explicit ShareResource(const char* str) {
         m_resource = make_shared<string>(str);
     }
  
     ShareResource(const ShareResource& resource) {
         if (this == &resource)
             return;
         m_resource = resource.m_resource;
     }
  
     ShareResource& operator=(const ShareResource& resource) {
         if (this == &resource)
             return *this;
         m_resource = resource.m_resource;
         return *this;
     }
  
     void read() const 
     {
         cout << "读取内容: " << *m_resource << endl;
         cout << "引用计数: " << m_resource.use_count() << endl;
     }
  
     void write(const char* str) 
     {
         cout << "写入前引用计数: " << m_resource.use_count() << endl;
          
         if (m_resource.use_count() > 1) 
         {
             // 资源被多个对象共享，创建新的副本
             string tmp = *m_resource;
             m_resource = make_shared<string>(tmp + str);
         }
         else {
             // 资源只被当前对象使用，直接修改
             *m_resource += str;
         }
 
         cout << "写入后引用计数: " << m_resource.use_count() << endl;
     }
  
     string getContent() const { return *m_resource;}
  
     void setContent(const char* str) 
     {
         cout << "设置内容前引用计数: " << m_resource.use_count() << endl;
  
         if (m_resource.use_count() > 1) 
         {
             // 资源被多个对象共享，创建新的副本
             m_resource = make_shared<string>(str);
         }
         else {
             // 资源只被当前对象使用，直接修改
             *m_resource = str;
         }
 
         cout << "设置内容后引用计数: " << m_resource.use_count() << endl;
     }
 
 private:
     shared_ptr<string> m_resource;  // 共享资源
 };
 
 int main() 
 {
     ShareResource r1("abc");
     cout << "初始资源状态:" << endl;
     r1.read();
 
     // 测试拷贝构造
     ShareResource r2(r1);
     cout << "\n拷贝构造后状态:" << endl;
     r2.read();
 
     // 测试多次拷贝
     ShareResource r3(r2);
     cout << "\n多次拷贝后状态:" << endl;
     r3.read();
 
     // 测试写入操作 - 此时资源被多个对象共享
     cout << "写入操作后状态 :" << endl;
     r3.write("hello");
     r3.read();
     r2.read();
     r1.read();
 
     // 测试写入操作 - 此时资源只被一个对象使用
     cout << "写入操作后状态 :" << endl;
     ShareResource r4("xyz");
     r4.write("123");
     r4.read();
 
     // 测试设置内容操作
  
     r3.setContent("new content");
     r3.read();
     r2.read();
     r1.read();
 
     cout << "\n最终资源状态:" << endl;
     r3.read();
 
     return 0;
 }